<?php
require_once(APPLICATION_PATH . '/../library/tcpdf/tcpdf_include.php');
class AdminController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action admroller here */
        $this->list_sess_unset('controller_admin');
        $this->session_search_key = 'controller_admin';
        $this->session_search_name = 'search_label';
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'admin', '');
    }

    public function viewAction() {
        if ($this->_getParam('adm_id') && $this->_getParam('adm_id') != "") {
            $adm_id = $this->_getParam('adm_id');
        } else {
            $this->_helper->redirector('list', 'admin', '');
        }
        $adminModel = new Model_Admin();
        $adminalldata = $adminModel->fetchEntryByViewId($adm_id);
        $updated_id = $adminalldata['lgn_id'];
        $login_type = $adminalldata['lgn_type'];

        /*         * get user name which is updated data* */
        $loginModel = new Model_Login();
        $updated_by_user = $loginModel->getUserData(Array('lgn_id' => $updated_id));
        $user_name = ucfirst($updated_by_user->name) . " [" . ucfirst($updated_by_user->role) . "]";
        $this->view->admindata = $user_name;
        $this->view->adminalldata = $adminalldata;
    }

    public function listAction() {

        $errorMessage = Array();
        $successmessage = "";
        $where = "";
        $searchtype = "";
        $orderField = 'adm_id';
        $sort = 'asc';
        
        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
        }


        /* Pagination Login */

        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
        $currentPageReviews = 1;
        //PAGING_PER_PAGE
        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }
        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;

        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = $this->ZFTRANSLATE->translate("select_one_checkbox");
                }
            }
            /* Search Facility Over Here */
            if ($postedData["searchtype"] == "") {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'] = "";
            }
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] != "")) {
                $searchtype = $postedData["searchtype"];
                $where = "adm_firstname LIKE '%$searchtype%' OR lgn_email LIKE '%$searchtype%' ";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'] = $searchtype;
                $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'];
            }
        } else {
            if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'])) {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'] = '';
            }
            $searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'];
            $where = "adm_firstname LIKE '%$searchtype%' OR lgn_email LIKE '%$searchtype%' ";
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'] = $searchtype;
            $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['search_txt1'];
        }

        $adminModel = new Model_Admin();
        $adminsData = $adminModel->fetchAdmin($where, $itemsPerPageReviews, $offset, $orderField, $sort);
        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($adminModel->getAdminCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('admroller' => 'admin', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);
        $paginator->paginate($link);

        $this->view->paginator = $paginator;
        $this->view->adminsData = $adminsData;
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $adminModel->getStatusArray();
        $this->view->searchtype = $searchtype;
    }

    public function deleteAction($ids = Array()) {
        //Load Admin Model 
        $adminModel = new Model_Admin();
        $adm_id = $this->_getParam('adm_id');
        $adminData = $adminModel->fetchEntryById($adm_id);
        /* if admin is superadmin then redirect to list page without deleting */
        if ($adminData['adm_issuperadmin'] == 1) {
            $this->_helper->redirector('list', 'admin', '');
        } else {
            if ($this->_getParam('adm_id') && $this->_getParam('adm_id') != "") {
                $adm_id = $this->_getParam('adm_id');
                $adminModel->deleteAdmin($adm_id);
                $this->addSuccessMessage($this->ZFTRANSLATE->translate("admin_delete_success"));
                $this->_helper->redirector('list', 'admin', '');
            } else {
                $adminModel->deleteAdmin($ids);
                $this->addSuccessMessage($this->ZFTRANSLATE->translate("admin_delete_success"));
                $this->_helper->redirector('list', 'admin', '');
            }
        }
    }

    public function formAction() {

        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $adminData = Array();
        $this->view->mode = "Add";
        $admin_issuperadmin = '';
        //Load login Model
        $loginModel = new Model_Login();

        //Load Admin Model
        $adminModel = new Model_Admin();

        //Load Admin Form
        $adminForm = new Form_AdminForm();

        //Load the country array for the select box in form 
        $countryArray = $adminModel->getcountryArray();
        $adminForm->adm_country->addMultiOptions($countryArray);

        //Load the status array for the select box in form 
        $statusArray = $adminModel->getStatusArray();
        $adminForm->adm_status->addMultiOptions($statusArray);

        //Load the language array for the select box in form 
        $languageArray = $adminModel->getlanguageArray();
        $adminForm->lang_id->addMultiOptions($languageArray);


        //Check for the admin Parameter
        $adminData['adm_id'] = $this->_request->getParam('adm_id');
        $adm_id = (!empty($adminData['adm_id'])) ? $adminData['adm_id'] : null;

        if (!empty($adm_id)) {
            //Set the Mode to Edit
            $adminForm->lgn_email->setAttribs(Array('readonly' => true));
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $adminModel->fetchEntryById($adm_id);
            $lgn_id = $data['lgn_id'];
            $currentEmail = $data['lgn_email'];
            $admin_issuperadmin = $data['adm_issuperadmin'];
            // $data['lgn_email_update'] = $data['lgn_email'];
            $data['adm_status'] = $data['lgn_active'];
        }
        //Populate form 
        $this->view->form = $adminForm->populate($data);
        if ($this->getRequest()->isPost()) {

            //Check for Errors
            $postedData = $this->_request->getPost();

            if (!$adminForm->isValid($postedData)) {
                $errorMessage = $adminForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {
                if ($this->view->mode == "Add") {
                    //Check for the email exist while Adding admin
                    $adminExist = $loginModel->checkEmailExist($postedData['lgn_email']);
                    if ($adminExist) {
                        $errorMessageArray[] = $this->ZFTRANSLATE->translate("email_check");
                    }
                    //Password Validation
                    if ($postedData['lgn_password'] == "") {
                        $errorMessageArray[] = $this->ZFTRANSLATE->translate("admin_required_password");
                    }
                    if ($postedData['lgn_password'] != "") {

                        if ($postedData['lgn_confirmpassword'] == "") {
                            $errorMessageArray[] = $this->ZFTRANSLATE->translate("admin_required_conf_password");
                        }

                        if ($postedData['lgn_password'] != $postedData['lgn_confirmpassword']) {
                            $errorMessageArray[] = $this->ZFTRANSLATE->translate("admin_required_match_password");
                        }
                    }
                }

                if (count($errorMessageArray) > 0) {
                    
                } else {
                    if ($this->view->mode == "Add") {
                        $adminData['adm_createddate'] = date("Y-m-d H:i:s");
                        $password = ($postedData['lgn_password'] == "") ? "" : md5($postedData['lgn_password']);
                        $loginData['lgn_email'] = $postedData['lgn_email'];
                        $loginData['lgn_password'] = $password;
                        $loginData['lgn_type'] = '1';
                        $loginData['lgn_created'] = date("Y-m-d H:i:s");
                        $loginData['lgn_modified'] = date("Y-m-d H:i:s");
                        $loginData['lgn_active'] = $postedData['adm_status']; //$postedData['lgn_active'];
                        $lgn_id = $loginModel->save($loginData, 'lgn_id');
                    } else {
                        if ($postedData['lgn_password'] != "") {
                            $password = md5($postedData['lgn_password']);
                            $loginData['lgn_email'] = $postedData['lgn_email'];
                            $loginData['lgn_id'] = $lgn_id;
                            $loginData['lgn_password'] = $password;
                            $loginData['lgn_type'] = '1';
                            $loginData['lgn_modified'] = date("Y-m-d H:i:s");
                            $loginData['lgn_active'] = $postedData['adm_status']; //$postedData['lgn_active'];
                            $lgn_id = $loginModel->save($loginData, 'lgn_id');
                        } else {
                            $loginData['lgn_id'] = $lgn_id;
                            $loginData['lgn_active'] = $postedData['adm_status'];
                            $lgn_id = $loginModel->save($loginData, 'lgn_id');
                        }
                    }

                    /*                     * authentication login id */
                    $updated_userid = $this->USER->lgn_id;
                    //Admin save
                    $adminData['updated_lgn_id'] = $updated_userid;
                    $adminData['adm_id'] = $adm_id;
                    $adminData['lgn_id'] = $lgn_id;
                    $adminData['lang_id'] = $postedData['lang_id'];
                    $adminData['adm_firstname'] = $postedData['adm_firstname'];
                    $adminData['adm_lastname'] = $postedData['adm_lastname'];
                    $adminData['adm_phone'] = $postedData['adm_phone'];
                    $adminData['adm_address'] = $postedData['adm_address'];
                    $adminData['adm_city'] = $postedData['adm_city'];
                    $adminData['adm_state'] = $postedData['adm_state'];
                    $adminData['adm_country'] = $postedData['adm_country'];
                    $adminData['adm_zipcode'] = $postedData['adm_zipcode'];
                    // $adminData['adm_status'] = $postedData['adm_status'];
                    $adminData['adm_updateddate'] = date("Y-m-d H:i:s");
                    $adminModel->save($adminData, 'adm_id');

                    if ($this->view->mode == "Add") {
                        $successmessage = $this->ZFTRANSLATE->translate("admin_add_success");
                    } else {
                        $successmessage = $this->ZFTRANSLATE->translate("admin_update_success");
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'admin', '');
                }
            }
        }
        /*         * * *  
         * if admin is superadmin then redirect to list page
         * * * */
        if ($admin_issuperadmin == 1) {
            $this->_helper->redirector('list', 'admin', '');
        } else {
            $this->view->mode = $this->view->mode;
            $this->view->roletype = $this->USER->roletype;
            $this->view->login_userid = $this->USER->usr_id;
            $this->view->adminid = $adm_id;
            $this->view->errorMessageArray = $errorMessageArray;
            $this->view->succesMessage = $successmessage;
            $this->view->form = $adminForm;
        }
    }

    public function editprofileAction() {

        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $adminData = Array();
        $this->view->mode = "Add";

        //Load login Model
        $loginModel = new Model_Login();

        //Load Admin Model
        $adminModel = new Model_Admin();

        //Load Admin Form
        $adminForm = new Form_AdminForm();

        //Load the country array for the select box in form 
        $countryArray = $adminModel->getcountryArray();
        $adminForm->adm_country->addMultiOptions($countryArray);
        //Load the status array for the select box in form 
        $statusArray = $adminModel->getStatusArray();
        $adminForm->adm_status->addMultiOptions($statusArray);

        //Load the language array for the select box in form 
        $languageArray = $adminModel->getlanguageArray();
        $adminForm->lang_id->addMultiOptions($languageArray);


        if ($this->USER->role == 'ADMIN') {
            //Check for the admin Parameter
            $admin_id_model = $adminModel->getadminId($this->USER->lgn_id);
            //$adminData['adm_id'] = $this->_request->getParam('adm_id');
            $adminData['adm_id'] = $admin_id_model['adm_id'];
            $adm_id = (!empty($adminData['adm_id'])) ? $adminData['adm_id'] : null;
        } else {
            $adm_id = '';
        }
        if (!empty($adm_id)) {
            $adminForm->lgn_email->setAttribs(Array('readonly' => true));
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $adminModel->fetchEntryById($adm_id);
            $lgn_id = $data['lgn_id'];
            $currentEmail = $data['lgn_email'];
        }


        //Populate form 
        $this->view->form = $adminForm->populate($data);
        if ($this->getRequest()->isPost()) {

            //Check for Errors
            $postedData = $this->_request->getPost();

            if (!$adminForm->isValid($postedData)) {
                $errorMessage = $adminForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {
                if ($this->view->mode == "Add") {
                    //Check for the email exist while Adding custoemr
                    $adminExist = $loginModel->checkEmailExist($postedData['lgn_email']);
                    if ($adminExist) {
                        $errorMessageArray[] = $this->ZFTRANSLATE->translate("email_check");
                    }
                    //Password Validation
                    if ($postedData['lgn_password'] == "") {
                        $errorMessageArray[] = $this->ZFTRANSLATE->translate("admin_required_password");
                    }
                    if ($postedData['lgn_password'] != "") {

                        if ($postedData['lgn_confirmpassword'] == "") {
                            $errorMessageArray[] = $this->ZFTRANSLATE->translate("admin_required_conf_password");
                        }

                        if ($postedData['lgn_password'] != $postedData['lgn_confirmpassword']) {
                            $errorMessageArray[] = $this->ZFTRANSLATE->translate("admin_required_match_password"); #"Confirm passwords don't match with password.";
                        }
                    }
                }

                if (count($errorMessageArray) > 0) {
                    
                } else {
                    if ($this->view->mode == "Add") {
                        $AdminCount = $adminModel->getAdminCount('');
                        if ($AdminCount == 0) {
                            $adminData['adm_isadmin'] = 1;
                        }
                        $adminData['adm_createddate'] = date("Y-m-d H:i:s");
                        $password = ($postedData['lgn_password'] == "") ? "" : md5($postedData['lgn_password']);
                        $loginData['lgn_email'] = $postedData['lgn_email'];
                        $loginData['lgn_password'] = $password;
                        $loginData['lgn_type'] = '1';
                        $loginData['lgn_created'] = date("Y-m-d H:i:s");
                        $loginData['lgn_modified'] = date("Y-m-d H:i:s");
                        $loginData['lgn_active'] = $postedData['adm_status']; //$postedData['lgn_active'];
                        $lgn_id = $loginModel->save($loginData, 'lgn_id');
                    } else {
                        if ($postedData['lgn_password'] != "") {
                            $password = md5($postedData['lgn_password']);
                            $loginData['lgn_email'] = $postedData['lgn_email'];
                            $loginData['lgn_id'] = $lgn_id;
                            $loginData['lgn_password'] = $password;
                            $loginData['lgn_type'] = '1';
                            $loginData['lgn_modified'] = date("Y-m-d H:i:s");
                            $loginData['lgn_active'] = $postedData['adm_status']; //$postedData['lgn_active'];
                            $lgn_id = $loginModel->save($loginData, 'lgn_id');
                        } else {
                            $loginData['lgn_id'] = $lgn_id;
                            $loginData['lgn_active'] = 1;
                            $lgn_id = $loginModel->save($loginData, 'lgn_id');
                        }
                    }

                    //Admin save
                    /*                     * *******update language id and code in session************** */
                    $dataUpdate = array();
                    $authData = Zend_Auth::getInstance()->getIdentity();
                    /* Language code */
                    $languageModel = new Model_Language();
                    $where = 'lang_id=' . $postedData['lang_id'];
                    $languagedefaultArray = $languageModel->fetchType($where);
                    $authData->usr_lang_id = $postedData['lang_id'];
                    $authData->usr_lang_code = strtolower($languagedefaultArray[0]['lang_code']);
                    $authData->language = strtolower($languagedefaultArray[0]['lang_code']);
                    $dataUpdate['usr_lang_id'] = $postedData['lang_id'];
                    $dataUpdate['usr_lang_code'] = strtolower($languagedefaultArray[0]['lang_code']);
                    $dataUpdate['language'] = strtolower($languagedefaultArray[0]['lang_code']);
                    //  $adminModel->save($dataUpdate, 'lgn_id');
                    /*                     * ************************************************************ */
                    $updated_userid = $this->USER->lgn_id;

                    //Admin save
                    $adminData['updated_lgn_id'] = $updated_userid;
                    $adminData['adm_id'] = $adm_id;
                    $adminData['lgn_id'] = $lgn_id;
                    $adminData['lang_id'] = $postedData['lang_id'];
                    $adminData['adm_firstname'] = $postedData['adm_firstname'];
                    $adminData['adm_lastname'] = $postedData['adm_lastname'];
                    $adminData['adm_phone'] = $postedData['adm_phone'];
                    $adminData['adm_address'] = $postedData['adm_address'];
                    $adminData['adm_city'] = $postedData['adm_city'];
                    $adminData['adm_state'] = $postedData['adm_state'];
                    $adminData['adm_country'] = $postedData['adm_country'];
                    $adminData['adm_zipcode'] = $postedData['adm_zipcode'];
                    // $adminData['adm_status'] = $postedData['adm_status'];
                    $adminData['adm_updateddate'] = date("Y-m-d H:i:s");
                    $adminModel->save($adminData, 'adm_id');

                    if ($this->view->mode == "Add") {
                        $successmessage = $this->ZFTRANSLATE->translate("adm_add_success");
                    } else {
                        $successmessage = $this->ZFTRANSLATE->translate("admin_update_success");
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'admin', '');
                }
            }
        }

        if ($this->USER->role == "ADMIN") {
            $this->view->USER_ROLE = $this->USER->role;
            $this->view->adminid = $adm_id;
            $this->view->errorMessageArray = $errorMessageArray;
            $this->view->succesMessage = $successmessage;
            $this->view->form = $adminForm;
        } else {
            /*             * * *  
             * if logged user is not admin then redirect to list page
             * * * */
            $this->_helper->redirector('list', 'admin', '');
        }
    }
    
    public function  dashboardAction(){
        
        $requestData = array();
        $orderField = 'req_id';
        $sort = 'asc';
        $where = '1=1 ';
        //$this->view->frm_date = date('Y-m-d',strtotime(' -1 day'));
        //$this->view->to_date = date('Y-m-d');
        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
        }
        
        /* Pagination Login */
        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
        $currentPageReviews = 1;

        //PAGING_PER_PAGE
        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }
        
       

        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;

       //$where, $itemsPerPageReviews, $offset, $orderField, $sort
        
        $requestModel = new Model_Request();
        $requestAssignmodel = new Model_Assignrequest();
        
        //search functionality
        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            if($postedData["dash_comment"] == ''){
              $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'] = '';
            }
            if($postedData["frm_date"] == ''){
              $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'] = '';
            }
            if($postedData["to_date"] == ''){
              $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'] = '';
            }
            if($postedData["req_reference"]== ''){
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'] = '';
               // $this->view->req_ref = '';
            }if($postedData["site_id"]== ''){
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'] = '';
                //$this->view->site_id = '';
            }if($postedData["subj_id"]== ''){
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'] = '';
               // $this->view->subj_id = '';    
            }if($postedData["ass_status"]== ''){
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'] = '';
               // $this->view->ass_status = '';    
            }
            if (isset($postedData["dash_comment"]) && $postedData["dash_comment"]!= '' ) {
                $searchtype = $postedData["dash_comment"];
                $where .= " and req_comment LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'] = $searchtype;
                $this->view->dash_comment = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'];
            }
            if (isset($postedData["frm_date"]) && $postedData["frm_date"]!= '' && isset($postedData["to_date"])&&  $postedData["to_date"]!= '' ) {
                $frm_date = $postedData["frm_date"];
                $to_date = $postedData["to_date"];
                $where .= " and req_date BETWEEN '".$frm_date."' and '".$to_date."' ";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'] = $frm_date;
                $this->view->frm_date = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'];
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'] = $to_date;
                $this->view->to_date = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'];
            }
            
            if (isset($postedData["req_reference"]) && $postedData["req_reference"]!= '' ) {
                $searchtype = $postedData["req_reference"];
                $where .= " and req_reference LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'] = $searchtype;
                $this->view->req_ref = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'];
            }
            if (isset($postedData["site_id"]) && $postedData["site_id"]!= '' ) {
                $searchtype = $postedData["site_id"];
                $where .= " and request.site_id LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'] = $searchtype;
                $this->view->site_id = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'];
            }
            if (isset($postedData["subj_id"]) && $postedData["subj_id"]!= '' ) {
                $searchtype = $postedData["subj_id"];
                $where .= " and request.subj_id LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'] = $searchtype;
                $this->view->subj_id = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'];
            }
            if (isset($postedData["ass_status"]) && $postedData["ass_status"]!= '' ) {
                $searchtype = $postedData["ass_status"];
                $where .= " and ass_status LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'] = $searchtype;
                $this->view->ass_status = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'];
            }

        } 
        else{
            $session_search = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            if(isset($session_search["frm_date"]) && $session_search["frm_date"] == ''){
                $session_search["frm_date"] = date('Y-m-d',strtotime(' -1 day'));
            }
            
            if(isset($session_search["to_date"]) && $session_search["to_date"] == ''){
                $session_search["to_date"] = date('Y-m-d');
            }
            
            if (isset($session_search["dash_comment"]) && $session_search["dash_comment"]!= '' ) {
                $searchtype = $session_search["dash_comment"];
                $where .= " and req_comment LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'] = $searchtype;
                $this->view->dash_comment = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'];
            }
            if (isset($session_search["frm_date"]) && $session_search["frm_date"]!= '' && isset($session_search["to_date"])&&  $session_search["to_date"]!= '' ) {
                $frm_date = $session_search["frm_date"];
                $to_date = $session_search["to_date"];
                $where .= " and req_date BETWEEN '".$frm_date."' and '".$to_date."' ";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'] = $frm_date;
                $this->view->frm_date = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'];
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'] = $to_date;
                $this->view->to_date = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'];
            }
            if (isset($session_search["req_ref"]) && ($session_search["req_ref"] != "")) {
                $searchtype = $session_search["req_ref"];
                $where .= " and req_reference LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'] = $searchtype;
                $this->view->req_ref = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'];
            }
            if (isset($session_search["site_id"]) && ($session_search["site_id"] != "")) {
                $searchtype = $session_search["site_id"];
                $where .= " and request.site_id LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'] = $searchtype;
                $this->view->site_id = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'];
            }
            if (isset($session_search["subj_id"]) && ($session_search["subj_id"] != "")) {
                $searchtype = $session_search["subj_id"];
                $where .= " and request.subj_id LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'] = $searchtype;
                $this->view->subj_id = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'];
            }
            if (isset($session_search["ass_status"]) && ($session_search["ass_status"] != "")) {
                $searchtype = $session_search["ass_status"];
                $where .= " and ass_status LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'] = $searchtype;
                $this->view->ass_status = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'];
            }
           
        } 
        
        
        
        $requestData = $requestModel->fetchRequestWithassign($where,$itemsPerPageReviews, $offset, $orderField, $sort);
        
        //search dropdown
        
        $searchrequestData = $requestModel->fetchRequestWithassign('',$itemsPerPageReviews, $offset, $orderField, $sort);

        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($requestModel->getRequestWithassignCount(''));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'admin', 'action' => 'dashboard', 'page' => 'PAGENO'), 'default', false);
        $paginator->paginate($link);

        
        $this->view->assignstatus = $requestAssignmodel->getStatusArray();
        $this->view->paginator = $paginator;
        $this->view->searchrequestData = $searchrequestData;
        $this->view->requestData = $requestData;
    }
    
    public function downloadpdfAction(){
    
        $requestModel = new Model_Request();
        $requestlogModel = new Model_Requestlog();
        $requestcommentModel = new Model_Requestcomment();
        $metaModel = new Model_Metadata();
        $metaData = $metaModel->fetchEntryByKey("HEADER_LOGO");
        $Header_Logo = $metaData['mtd_value'];
        $where = "1=1 ";
        $session_search = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            
            if (isset($session_search["dash_comment"]) && $session_search["dash_comment"]!= '' ) {
                $searchtype = $session_search["dash_comment"];
                $where .= " and req_comment LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'] = $searchtype;
                $this->view->dash_comment = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['dash_comment'];
            }
            if (isset($session_search["frm_date"]) && $session_search["frm_date"]!= '' && isset($session_search["to_date"])&&  $session_search["to_date"]!= '' ) {
                $frm_date = $session_search["frm_date"];
                $to_date = $session_search["to_date"];
                $where .= " and req_date BETWEEN '".$frm_date."' and '".$to_date."' ";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'] = $frm_date;
                $this->view->frm_date = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['frm_date'];
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'] = $to_date;
                $this->view->to_date = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['to_date'];
            }
            if (isset($session_search["req_ref"]) && ($session_search["req_ref"] != "")) {
                $searchtype = $session_search["req_ref"];
                $where .= " and req_reference LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'] = $searchtype;
                $this->view->req_ref = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['req_ref'];
            }
            if (isset($session_search["site_id"]) && ($session_search["site_id"] != "")) {
                $searchtype = $session_search["site_id"];
                $where .= " and request.site_id LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'] = $searchtype;
                $this->view->site_id = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['site_id'];
            }
            if (isset($session_search["subj_id"]) && ($session_search["subj_id"] != "")) {
                $searchtype = $session_search["subj_id"];
                $where .= " and request.subj_id LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'] = $searchtype;
                $this->view->subj_id = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['subj_id'];
            }
            if (isset($session_search["ass_status"]) && ($session_search["ass_status"] != "")) {
                $searchtype = $session_search["ass_status"];
                $where .= " and ass_status LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'] = $searchtype;
                $this->view->ass_status = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['ass_status'];
            }
        $requestData = $requestModel->fetchRequestWithassign($where);
        
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->SetTitle('SERVICE-APP');

        // set default header data
       if($Header_Logo != ''){
           $image = $this->view->PUBLIC_PATH . "upload/logo/".$Header_Logo;
           $pdf->SetHeaderData($image, '', '', '');
       }else{
           $pdf->SetHeaderData('', '', PDF_HEADER_TITLE, '');
       }
      
        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        // set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        // set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        $pdf->SetFont('dejavusans', '', 10);

        // add a page
        $pdf->AddPage();

        $html = '<h1>Request Detail</h1>';

        $pdf->writeHTML($html, true, false, true, false, '');
       
         

        foreach($requestData as $key =>$value){
           //$requestidData = $requestModel->fetchEntryByViewId($value['req_id']);
            $html = '
               <b>New  Request '.$value['req_reference'].'</b> <br/><br/>
        <table border="0" cellspacing="1" cellpadding="1">
            <tr>
                <th><b>Request Ref.</b></th>
                <th><b>Date</b></th>
                <th><b>Site Name</b></th>
                <th><b>Subject Name</b></th>
                <th><b>Added By</b></th>
                <th><b>Assign To</b></th>
                <th><b>Status</b></th>
                   </tr>';
         $req_hist = '<b>Request History:</b><br/><br/>
                        <table border="0" cellspacing="1" cellpadding="1">
                            <tr>
                                <th><b>Date</b></th>
                                <th><b>Assign By</b></th>
                                <th><b>Assign To</b></th>
                                <th><b>Status</b></th>
                           </tr>';
           
         //Status
                $status = '<span color="red">Pending</span>';
                if ($value['ass_status'] == 3){
                    $status = 'Done';
                }if ($value['ass_status'] == 4){
                    $status = 'Pending';
                }if ($value['ass_status'] == 5){
                    $status = 'In Progress';
                }if ($value['ass_status'] == 6){
                    $status = 'Assign';
                }if ($value['ass_status'] == 7){
                    $status = 'Seen';
                }
                
                if($value['cont_firstname'] != ''){
                    $ass_to = ucfirst($value['cont_firstname']." ".$value['cont_lastname']);
                }else if($value['cust_firstname'] != ''){
                    $ass_to = ucfirst($value['cust_firstname']." ".$value['cust_lastname']);
                }else{
                    $ass_to = '<span color="red">Pending</span>';
                }
                
                
            $html .= ' <tr>
                        <td>'.$value['req_reference'].'</td>
                        <td>'.$value['req_date'].' '.date('h:i',strtotime($value['req_createddate'])).'</td>
                        <td>'.$value['site_name'].'</td>
                        <td>'.$value['subj_name'].'</td>
                        <td>'.ucfirst($value['com_name']).'</td>
                        <td>'.$ass_to.'</td>
                        <td>'.$status.'</td>
                    </tr>';
            
            //Request Log
            $where_log = "req_id = ".$value['req_id'];
            $requestlogData = $requestlogModel->fetchRequestlog($where_log);
            if(count($requestlogData) >0){
            foreach($requestlogData as $log_key => $log_value){
            //Ass By      
                if( $log_value['ass_by'] == 1){
                  $ass_by_name =  'Admin' . " ( ".ucfirst($log_value['update_adm_firstname']." ".$log_value['update_adm_lastname'])." )";  
                }
                if( $log_value['ass_by'] == 2 || $log_value['ass_by'] == 3){
                 $ass_by_name = 'Contractor'. " ( ".ucfirst($log_value['update_cont_firstname']." ".$log_value['update_cont_lastname'])." )";  
                }

                //Status
                if ($log_value['ass_type'] == 3){
                    $ass_type = 'Done';
                }if ($log_value['ass_type'] == 4){
                    $ass_type = 'Pending';
                }if ($log_value['ass_type'] == 5){
                    $ass_type = 'In Progress';
                }if ($log_value['ass_type'] == 6){
                    $ass_type = 'Assign';
                }if ($log_value['ass_type'] == 7){
                    $ass_type = 'Seen';
                }
            
                $req_hist .='<tr>
                    <td>'.date('Y-m-d H:i', strtotime($log_value['log_createddate'])).'</td>
                    <td>'.$ass_by_name.'</td>
                    <td>'.ucfirst($log_value['cont_firstname']." ".$log_value['cont_lastname']).'</td>
                    <td><span color="red">'.$ass_type.'</span></td>
                </tr>';
            }
            }
            else{
                 $req_hist .='<tr>
                    <td colspan="4">No Record Found</td></tr>';
            }
            
            
            $comment = '<h3>Comments</h3>';

           
            $html .= '</table>';
            $req_hist .= '</table>';
            $pdf->writeHTML($html, true, false, true, false, '');
            $pdf->writeHTML($req_hist, true, false, true, false, '');
            $pdf->writeHTML($comment, true, false, true, false, '');
            
            
            $requestCommentData = $requestcommentModel->fetchRequestComment($where_log);
            
            if(count($requestCommentData) >0){
                foreach($requestCommentData as $cmt_key => $cmt_value){
                    $leftcol =  '<b>'.ucfirst($cmt_value['Name']).' </b><span color="red"> '.$cmt_value['Addedby'].'</span>';
                    $rightcol = ''.date('Y-m-d H:i',  strtotime($cmt_value['createDate'])).'';
                    $y = $pdf->getY();
                    $pdf->SetFillColor(255, 255, 255);
            
                    $pdf->writeHTMLCell(150, '', '', $y, $leftcol, 0, 0, 1, true, 'J', true);
                    $pdf->writeHTMLCell(80, '', '', '', $rightcol, 0, 1, 1, true, 'J', true);
            
                    
                    $add_attch = '' ;
                    if ($cmt_value['cmnt_add_attachment'] != ''){
                        $add_attch = '<p>
                            <a target="_blank" href="'.$this->view->BASE_URL.'public/upload/comment_attachment/'.$cmt_value['cmnt_add_attachment'].'">View Attachment</a>
                                </p>';
                    }else{
                        $add_attch = '' ;
                    }                            
                                                
                    $comment_data ='<style>   
                        div.mainclass {
                            border-style: solid;
                            border-width: 1px;
                            border-color: #000;
                                    width : 100%;
                        }
                    </style>
                    <div>  '.$cmt_value['comment'].'</div>
                     '.$add_attch.'
                    <div class="mainclass"></div>';
                    
                    $pdf->writeHTML($comment_data, true, false, true, false, '');
                }
            }else{
                $comment_data = '<br/><br/>No Comment Found.';
                $pdf->writeHTML($comment_data, true, false, true, false, '');
            }
            if(count($requestData) != ($key+1)){
                $pdf->AddPage();
            }
          
                   
        }  
     $pdf->Output('Request.pdf', 'D');
       exit;     
    }

    public function deleterequestAction() {
        //Load Request Model 
        $requestModel = new Model_Request();
        if ($this->_getParam('req_id') && $this->_getParam('req_id') != "") {
            $request_id = $this->_getParam('req_id');
            $requestModel->deleteRequest($request_id);
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("req_delete_success"));
        }
        $this->_helper->redirector('dashboard', 'admin', '');
    }

     public function acknowledgeAction() {
        //Load Request Model 
        $requestModel = new Model_Request();
        if ($this->_getParam('req_id') && $this->_getParam('req_id') != "") {
            $request_id = $this->_getParam('req_id');
            $data = array('req_acknowledge' => '1');
            $requestModel->update($data, 'req_id =' . (int) $request_id);
            
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("req_acknowledge_success"));
        }
         if ($this->USER->role == 'ADMIN') {
            $this->_helper->redirector('dashboard', 'admin', '');
        } else if ($this->USER->role == 'CUSTOMER') {
            $this->_helper->redirector('dashboard', 'customer', '');
        } else {
            $this->_helper->redirector('dashboard', 'contractor', '');
        }
    }
    
    public function closerequestAction() {
        //Load Request Model 
        $requestModel = new Model_Request();
        if ($this->_getParam('req_id') && $this->_getParam('req_id') != "") {
            $request_id = $this->_getParam('req_id');
            $data = array('req_closerequest' => '1','closed_datetime'=>date('Y-m-d H:i:s'));
            $requestModel->update($data, 'req_id =' . (int) $request_id);
            
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("req_closed_success"));
        }
         if ($this->USER->role == 'ADMIN') {
            $this->_helper->redirector('dashboard', 'admin', '');
        } else if ($this->USER->role == 'CUSTOMER') {
            $this->_helper->redirector('dashboard', 'customer', '');
        } else {
            $this->_helper->redirector('dashboard', 'contractor', '');
        }
    }
   

}

?>